home *** CD-ROM | disk | FTP | other *** search
/ Champak 141 / (Vol 141) Oct 17 2011.iso / Games / guitar-geek.swf / scripts / mochi / MochiServices.as < prev   
Encoding:
Text File  |  2011-10-17  |  21.5 KB  |  667 lines

  1. package mochi
  2. {
  3.    import flash.display.DisplayObject;
  4.    import flash.display.DisplayObjectContainer;
  5.    import flash.display.Loader;
  6.    import flash.display.MovieClip;
  7.    import flash.display.Sprite;
  8.    import flash.events.Event;
  9.    import flash.events.IOErrorEvent;
  10.    import flash.events.StatusEvent;
  11.    import flash.events.TimerEvent;
  12.    import flash.net.LocalConnection;
  13.    import flash.net.URLRequest;
  14.    import flash.system.Capabilities;
  15.    import flash.system.Security;
  16.    import flash.utils.ByteArray;
  17.    import flash.utils.Endian;
  18.    import flash.utils.Timer;
  19.    import flash.utils.getTimer;
  20.    import flash.utils.setTimeout;
  21.    
  22.    public class MochiServices
  23.    {
  24.       
  25.       private static var _container:Object;
  26.       
  27.       private static var _connected:Boolean = false;
  28.       
  29.       private static var _swfVersion:String;
  30.       
  31.       private static var _sendChannel:LocalConnection;
  32.       
  33.       private static var _rcvChannelName:String;
  34.       
  35.       private static var _gatewayURL:String = "http://www.mochiads.com/static/lib/services/services.swf";
  36.       
  37.       private static var _clip:MovieClip;
  38.       
  39.       private static var _loader:Loader;
  40.       
  41.       private static var _id:String;
  42.       
  43.       private static var _listenChannel:LocalConnection;
  44.       
  45.       private static var _timer:Timer;
  46.       
  47.       private static var _sendChannelName:String;
  48.       
  49.       private static var _startTime:Number;
  50.       
  51.       private static var _connecting:Boolean = false;
  52.       
  53.       public static var onError:Object;
  54.       
  55.       private static var _listenChannelName:String = "__mochiservices";
  56.       
  57.       private static var _rcvChannel:LocalConnection;
  58.        
  59.       
  60.       public function MochiServices()
  61.       {
  62.          super();
  63.       }
  64.       
  65.       public static function isNetworkAvailable() : Boolean
  66.       {
  67.          return Security.sandboxType != "localWithFile";
  68.       }
  69.       
  70.       public static function send(methodName:String, args:Object = null, callbackObject:Object = null, callbackMethod:Object = null) : void
  71.       {
  72.          if(_connected)
  73.          {
  74.             _sendChannel.send(_sendChannelName,"onReceive",{
  75.                "methodName":methodName,
  76.                "args":args,
  77.                "callbackID":_clip._nextcallbackID
  78.             });
  79.          }
  80.          else
  81.          {
  82.             if(_clip == null || !_connecting)
  83.             {
  84.                onError("NotConnected");
  85.                handleError(args,callbackObject,callbackMethod);
  86.                flush(true);
  87.                return;
  88.             }
  89.             _clip._queue.push({
  90.                "methodName":methodName,
  91.                "args":args,
  92.                "callbackID":_clip._nextcallbackID
  93.             });
  94.          }
  95.          if(_clip != null)
  96.          {
  97.             if(_clip._callbacks != null && _clip._nextcallbackID != null)
  98.             {
  99.                _clip._callbacks[_clip._nextcallbackID] = {
  100.                   "callbackObject":callbackObject,
  101.                   "callbackMethod":callbackMethod
  102.                };
  103.                ++_clip._nextcallbackID;
  104.             }
  105.          }
  106.       }
  107.       
  108.       public static function get connected() : Boolean
  109.       {
  110.          return _connected;
  111.       }
  112.       
  113.       private static function flush(error:Boolean) : void
  114.       {
  115.          var request:Object = null;
  116.          var callback:Object = null;
  117.          if(_clip != null)
  118.          {
  119.             if(_clip._queue != null)
  120.             {
  121.                while(_clip._queue.length > 0)
  122.                {
  123.                   request = _clip._queue.shift();
  124.                   callback = null;
  125.                   if(request != null)
  126.                   {
  127.                      if(request.callbackID != null)
  128.                      {
  129.                         callback = _clip._callbacks[request.callbackID];
  130.                      }
  131.                      delete _clip._callbacks[request.callbackID];
  132.                      if(error && callback != null)
  133.                      {
  134.                         handleError(request.args,callback.callbackObject,callback.callbackMethod);
  135.                      }
  136.                   }
  137.                }
  138.             }
  139.          }
  140.       }
  141.       
  142.       private static function clickMovie(url:String, cb:Function) : MovieClip
  143.       {
  144.          var b:int = 0;
  145.          var loader:Loader = null;
  146.          var avm1_bytecode:Array = [150,21,0,7,1,0,0,0,0,98,116,110,0,7,2,0,0,0,0,116,104,105,115,0,28,150,22,0,0,99,114,101,97,116,101,69,109,112,116,121,77,111,118,105,101,67,108,105,112,0,82,135,1,0,0,23,150,13,0,4,0,0,111,110,82,101,108,101,97,115,101,0,142,8,0,0,0,0,2,42,0,114,0,150,17,0,0,32,0,7,1,0,0,0,8,0,0,115,112,108,105,116,0,82,135,1,0,1,23,150,7,0,4,1,7,0,0,0,0,78,150,8,0,0,95,98,108,97,110,107,0,154,1,0,0,150,7,0,0,99,108,105,99,107,0,150,7,0,4,1,7,1,0,0,0,78,150,27,0,7,2,0,0,0,7,0,0,0,0,0,76,111,99,97,108,67,111,110,110,101,99,116,105,111,110,0,64,150,6,0,0,115,101,110,100,0,82,79,150,15,0,4,0,0,95,97,108,112,104,97,0,7,0,0,0,0,79,150,23,0,7,255,0,255,0,7,1,0,0,0,4,0,0,98,101,103,105,110,70,105,108,108,0,82,23,150,25,0,7,0,0,0,0,7,0,0,0,0,7,2,0,0,0,4,0,0,109,111,118,101,84,111,0,82,23,150,25,0,7,100,0,0,0,7,0,0,0,0,7,2,0,0,0,4,0,0,108,105,110,101,84,111,0,82,23,150,25,0,7,100,0,0,0,7,100,0,0,0,7,2,0,0,0,4,0,0,108,105,110,101,84,111,0,82,23,150,25,0,7,0,0,0,0,7,100,0,0,0,7,2,0,0,0,4,0,0,108,105,110,101,84,111,0,82,23,150,25,0,7,0,0,0,0,7,0,0,0,0,7,2,0,0,0,4,0,0,108,105,110,101,84,111,0,82,23,150,16,0,7,0,0,0,0,4,0,0,101,110,100,70,105,108,108,0,82,23];
  147.          var header:Array = [104,0,31,64,0,7,208,0,0,12,1,0,67,2,255,255,255,63,3];
  148.          var footer:Array = [0,64,0,0,0];
  149.          var mc:MovieClip = new MovieClip();
  150.          var lc:LocalConnection = new LocalConnection();
  151.          var lc_name:String = "_click_" + Math.floor(Math.random() * 999999) + "_" + Math.floor(new Date().getTime());
  152.          lc = new LocalConnection();
  153.          mc.lc = lc;
  154.          mc.click = cb;
  155.          lc.client = mc;
  156.          lc.connect(lc_name);
  157.          var ba:ByteArray = new ByteArray();
  158.          var cpool:ByteArray = new ByteArray();
  159.          cpool.endian = Endian.LITTLE_ENDIAN;
  160.          cpool.writeShort(1);
  161.          cpool.writeUTFBytes(url + " " + lc_name);
  162.          cpool.writeByte(0);
  163.          var actionLength:uint = uint(avm1_bytecode.length + cpool.length + 4);
  164.          var fileLength:uint = uint(actionLength + 35);
  165.          ba.endian = Endian.LITTLE_ENDIAN;
  166.          ba.writeUTFBytes("FWS");
  167.          ba.writeByte(8);
  168.          ba.writeUnsignedInt(fileLength);
  169.          for each(b in header)
  170.          {
  171.             ba.writeByte(b);
  172.          }
  173.          ba.writeUnsignedInt(actionLength);
  174.          ba.writeByte(136);
  175.          ba.writeShort(cpool.length);
  176.          ba.writeBytes(cpool);
  177.          for each(b in avm1_bytecode)
  178.          {
  179.             ba.writeByte(b);
  180.          }
  181.          for each(b in footer)
  182.          {
  183.             ba.writeByte(b);
  184.          }
  185.          loader = new Loader();
  186.          loader.loadBytes(ba);
  187.          mc.addChild(loader);
  188.          return mc;
  189.       }
  190.       
  191.       private static function init(id:String, clip:Object) : void
  192.       {
  193.          _id = id;
  194.          if(clip != null)
  195.          {
  196.             _container = clip;
  197.             loadCommunicator(id,_container);
  198.          }
  199.       }
  200.       
  201.       public static function get childClip() : Object
  202.       {
  203.          return _clip;
  204.       }
  205.       
  206.       public static function get id() : String
  207.       {
  208.          return _id;
  209.       }
  210.       
  211.       public static function stayOnTop() : void
  212.       {
  213.          _container.addEventListener(Event.ENTER_FRAME,MochiServices.bringToTop,false,0,true);
  214.          if(_clip != null)
  215.          {
  216.             _clip.visible = true;
  217.          }
  218.       }
  219.       
  220.       public static function addLinkEvent(url:String, burl:String, btn:DisplayObjectContainer, onClick:Function = null) : void
  221.       {
  222.          var i:Number;
  223.          var netup:Boolean = false;
  224.          var s:String = null;
  225.          var x:String = null;
  226.          var req:URLRequest = null;
  227.          var loader:Loader = null;
  228.          var err:Function = null;
  229.          var complete:Function = null;
  230.          var setURL:Function = null;
  231.          var vars:Object = new Object();
  232.          vars["mav"] = getVersion();
  233.          vars["swfv"] = "9";
  234.          vars["swfurl"] = btn.loaderInfo.loaderURL;
  235.          vars["fv"] = Capabilities.version;
  236.          vars["os"] = Capabilities.os;
  237.          vars["lang"] = Capabilities.language;
  238.          vars["scres"] = Capabilities.screenResolutionX + "x" + Capabilities.screenResolutionY;
  239.          s = "?";
  240.          i = 0;
  241.          for(x in vars)
  242.          {
  243.             if(i != 0)
  244.             {
  245.                s += "&";
  246.             }
  247.             i++;
  248.             s = s + x + "=" + escape(vars[x]);
  249.          }
  250.          req = new URLRequest("http://x.mochiads.com/linkping.swf");
  251.          loader = new Loader();
  252.          err = function(ev:Object):void
  253.          {
  254.             netup = false;
  255.             ev.target.removeEventListener(ev.type,arguments.callee);
  256.          };
  257.          complete = function(ev:Object):void
  258.          {
  259.             netup = true;
  260.             ev.target.removeEventListener(ev.type,arguments.callee);
  261.          };
  262.          loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,err);
  263.          loader.contentLoaderInfo.addEventListener(Event.COMPLETE,complete);
  264.          loader.load(req);
  265.          setURL = function():void
  266.          {
  267.             var u:String = null;
  268.             if(netup)
  269.             {
  270.                u = url + s;
  271.             }
  272.             else
  273.             {
  274.                u = burl;
  275.             }
  276.             var avm1Click:DisplayObject = clickMovie(u,onClick);
  277.             btn.addChild(avm1Click);
  278.             avm1Click.scaleX = 0.01 * btn.width;
  279.             avm1Click.scaleY = 0.01 * btn.height;
  280.          };
  281.          setTimeout(setURL,1500);
  282.       }
  283.       
  284.       public static function getVersion() : String
  285.       {
  286.          return "1.35";
  287.       }
  288.       
  289.       public static function disconnect() : void
  290.       {
  291.          if(_connected || _connecting)
  292.          {
  293.             if(_clip != null)
  294.             {
  295.                if(_clip.parent != null)
  296.                {
  297.                   if(_clip.parent is Sprite)
  298.                   {
  299.                      Sprite(_clip.parent).removeChild(_clip);
  300.                      _clip = null;
  301.                   }
  302.                }
  303.             }
  304.             _connecting = _connected = false;
  305.             flush(true);
  306.             try
  307.             {
  308.                _listenChannel.close();
  309.                _rcvChannel.close();
  310.             }
  311.             catch(error:Error)
  312.             {
  313.             }
  314.          }
  315.          if(_timer != null)
  316.          {
  317.             try
  318.             {
  319.                _timer.stop();
  320.             }
  321.             catch(error:Error)
  322.             {
  323.             }
  324.          }
  325.       }
  326.       
  327.       public static function allowDomains(server:String) : String
  328.       {
  329.          var hostname:String = null;
  330.          Security.allowDomain("*");
  331.          Security.allowInsecureDomain("*");
  332.          if(server.indexOf("http://") != -1)
  333.          {
  334.             hostname = String(server.split("/")[2].split(":")[0]);
  335.             Security.allowDomain(hostname);
  336.             Security.allowInsecureDomain(hostname);
  337.          }
  338.          return hostname;
  339.       }
  340.       
  341.       public static function doClose() : void
  342.       {
  343.          _container.removeEventListener(Event.ENTER_FRAME,MochiServices.bringToTop);
  344.          if(_clip.parent != null)
  345.          {
  346.             Sprite(_clip.parent).removeChild(_clip);
  347.          }
  348.       }
  349.       
  350.       public static function setContainer(container:Object = null, doAdd:Boolean = true) : void
  351.       {
  352.          if(container != null)
  353.          {
  354.             if(container is Sprite)
  355.             {
  356.                _container = container;
  357.             }
  358.          }
  359.          if(doAdd)
  360.          {
  361.             if(_container is Sprite)
  362.             {
  363.                Sprite(_container).addChild(_clip);
  364.             }
  365.          }
  366.       }
  367.       
  368.       private static function onStatus(event:StatusEvent) : void
  369.       {
  370.          switch(event.level)
  371.          {
  372.             case "error":
  373.                _connected = false;
  374.                _listenChannel.connect(_listenChannelName);
  375.          }
  376.       }
  377.       
  378.       private static function initComChannels() : void
  379.       {
  380.          if(!_connected)
  381.          {
  382.             _sendChannel.addEventListener(StatusEvent.STATUS,MochiServices.onStatus);
  383.             _sendChannel.send(_sendChannelName,"onReceive",{"methodName":"handshakeDone"});
  384.             _sendChannel.send(_sendChannelName,"onReceive",{
  385.                "methodName":"registerGame",
  386.                "id":_id,
  387.                "clip":_container,
  388.                "version":getVersion(),
  389.                "parentURL":_container.loaderInfo.loaderURL
  390.             });
  391.             _rcvChannel.addEventListener(StatusEvent.STATUS,MochiServices.onStatus);
  392.             _clip.onReceive = function(pkg:Object):void
  393.             {
  394.                var method:*;
  395.                var obj:Object;
  396.                var methodName:String = null;
  397.                var cb:String = String(pkg.callbackID);
  398.                var cblst:Object = this.client._callbacks[cb];
  399.                if(!cblst)
  400.                {
  401.                   return;
  402.                }
  403.                method = cblst.callbackMethod;
  404.                methodName = "";
  405.                obj = cblst.callbackObject;
  406.                if(Boolean(obj) && typeof method == "string")
  407.                {
  408.                   methodName = method;
  409.                   if(obj[method] != null)
  410.                   {
  411.                      method = obj[method];
  412.                   }
  413.                   else
  414.                   {
  415.                      trace("Error: Method  " + method + " does not exist.");
  416.                   }
  417.                }
  418.                if(method != undefined)
  419.                {
  420.                   try
  421.                   {
  422.                      method.apply(obj,pkg.args);
  423.                   }
  424.                   catch(error:Error)
  425.                   {
  426.                      trace("Error invoking callback method \'" + methodName + "\': " + error.toString());
  427.                   }
  428.                }
  429.                else if(obj != null)
  430.                {
  431.                   try
  432.                   {
  433.                      obj(pkg.args);
  434.                   }
  435.                   catch(error:Error)
  436.                   {
  437.                      trace("Error invoking method on object: " + error.toString());
  438.                   }
  439.                }
  440.                delete this.client._callbacks[cb];
  441.             };
  442.             _clip.onError = function():void
  443.             {
  444.                MochiServices.onError("IOError");
  445.             };
  446.             _rcvChannel.connect(_rcvChannelName);
  447.             trace("connected!");
  448.             _connecting = false;
  449.             _connected = true;
  450.             _listenChannel.close();
  451.             while(_clip._queue.length > 0)
  452.             {
  453.                _sendChannel.send(_sendChannelName,"onReceive",_clip._queue.shift());
  454.             }
  455.          }
  456.       }
  457.       
  458.       private static function listen() : void
  459.       {
  460.          _listenChannel = new LocalConnection();
  461.          _listenChannel.client = _clip;
  462.          _clip.handshake = function(args:Object):void
  463.          {
  464.             MochiServices.comChannelName = args.newChannel;
  465.          };
  466.          _listenChannel.allowDomain("*","localhost");
  467.          _listenChannel.allowInsecureDomain("*","localhost");
  468.          _listenChannel.connect(_listenChannelName);
  469.          trace("Waiting for MochiAds services to connect...");
  470.       }
  471.       
  472.       private static function handleError(args:Object, callbackObject:Object, callbackMethod:Object) : void
  473.       {
  474.          if(args != null)
  475.          {
  476.             if(args.onError != null)
  477.             {
  478.                args.onError.apply(null,["NotConnected"]);
  479.             }
  480.             if(args.options != null && args.options.onError != null)
  481.             {
  482.                args.options.onError.apply(null,["NotConnected"]);
  483.             }
  484.          }
  485.          if(callbackMethod != null)
  486.          {
  487.             args = {};
  488.             args.error = true;
  489.             args.errorCode = "NotConnected";
  490.             if(callbackObject != null && callbackMethod is String)
  491.             {
  492.                try
  493.                {
  494.                   callbackObject[callbackMethod](args);
  495.                }
  496.                catch(error:Error)
  497.                {
  498.                }
  499.             }
  500.             else if(callbackMethod != null)
  501.             {
  502.                try
  503.                {
  504.                   callbackMethod.apply(args);
  505.                }
  506.                catch(error:Error)
  507.                {
  508.                }
  509.             }
  510.          }
  511.       }
  512.       
  513.       public static function get clip() : Object
  514.       {
  515.          return _container;
  516.       }
  517.       
  518.       public static function set comChannelName(val:String) : void
  519.       {
  520.          if(val != null)
  521.          {
  522.             if(val.length > 3)
  523.             {
  524.                _sendChannelName = val + "_fromgame";
  525.                _rcvChannelName = val;
  526.                initComChannels();
  527.             }
  528.          }
  529.       }
  530.       
  531.       private static function loadCommunicator(id:String, clip:Object) : MovieClip
  532.       {
  533.          var f:Function;
  534.          var req:URLRequest;
  535.          var clipname:String = "_mochiservices_com_" + id;
  536.          if(_clip != null)
  537.          {
  538.             return _clip;
  539.          }
  540.          if(!MochiServices.isNetworkAvailable())
  541.          {
  542.             return null;
  543.          }
  544.          MochiServices.allowDomains(_gatewayURL);
  545.          _clip = createEmptyMovieClip(clip,clipname,10336,false);
  546.          _loader = new Loader();
  547.          _timer = new Timer(1000,0);
  548.          _startTime = getTimer();
  549.          _timer.addEventListener(TimerEvent.TIMER,connectWait);
  550.          _timer.start();
  551.          f = function(ev:Object):void
  552.          {
  553.             _clip._mochiad_ctr_failed = true;
  554.             trace("MochiServices could not load.");
  555.             MochiServices.disconnect();
  556.             MochiServices.onError("IOError");
  557.          };
  558.          _loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,f);
  559.          req = new URLRequest(_gatewayURL);
  560.          _loader.load(req);
  561.          _clip.addChild(_loader);
  562.          _clip._mochiservices_com = _loader;
  563.          _sendChannel = new LocalConnection();
  564.          _clip._queue = [];
  565.          _rcvChannel = new LocalConnection();
  566.          _rcvChannel.allowDomain("*","localhost");
  567.          _rcvChannel.allowInsecureDomain("*","localhost");
  568.          _rcvChannel.client = _clip;
  569.          _clip._nextcallbackID = 0;
  570.          _clip._callbacks = {};
  571.          listen();
  572.          return _clip;
  573.       }
  574.       
  575.       public static function bringToTop(e:Event) : void
  576.       {
  577.          if(MochiServices.clip != null)
  578.          {
  579.             if(MochiServices.childClip != null)
  580.             {
  581.                try
  582.                {
  583.                   if(MochiServices.clip.numChildren > 1)
  584.                   {
  585.                      MochiServices.clip.setChildIndex(MochiServices.childClip,MochiServices.clip.numChildren - 1);
  586.                   }
  587.                }
  588.                catch(errorObject:Error)
  589.                {
  590.                   trace("Warning: Depth sort error.");
  591.                   _container.removeEventListener(Event.ENTER_FRAME,MochiServices.bringToTop);
  592.                }
  593.             }
  594.          }
  595.       }
  596.       
  597.       public static function connect(id:String, clip:Object, onError:Object = null) : void
  598.       {
  599.          if(clip is DisplayObject)
  600.          {
  601.             if(!_connected && _clip == null)
  602.             {
  603.                trace("MochiServices Connecting...");
  604.                _connecting = true;
  605.                init(id,clip);
  606.             }
  607.          }
  608.          else
  609.          {
  610.             trace("Error, MochiServices requires a Sprite, Movieclip or instance of the stage.");
  611.          }
  612.          if(onError != null)
  613.          {
  614.             MochiServices.onError = onError;
  615.          }
  616.          else if(MochiServices.onError == null)
  617.          {
  618.             MochiServices.onError = function(errorCode:String):void
  619.             {
  620.                trace(errorCode);
  621.             };
  622.          }
  623.       }
  624.       
  625.       public static function createEmptyMovieClip(parent:Object, name:String, depth:Number, doAdd:Boolean = true) : MovieClip
  626.       {
  627.          var mc:MovieClip = new MovieClip();
  628.          if(doAdd)
  629.          {
  630.             if(false && Boolean(depth))
  631.             {
  632.                parent.addChildAt(mc,depth);
  633.             }
  634.             else
  635.             {
  636.                parent.addChild(mc);
  637.             }
  638.          }
  639.          try
  640.          {
  641.             parent[name] = mc;
  642.          }
  643.          catch(e:Error)
  644.          {
  645.             throw new Error("MochiServices requires a clip that is an instance of a dynamic class.  If your class extends Sprite or MovieClip, you must make it dynamic.");
  646.          }
  647.          mc["_name"] = name;
  648.          return mc;
  649.       }
  650.       
  651.       public static function connectWait(e:TimerEvent) : void
  652.       {
  653.          if(getTimer() - _startTime > 10000)
  654.          {
  655.             if(!_connected)
  656.             {
  657.                _clip._mochiad_ctr_failed = true;
  658.                trace("MochiServices could not load.");
  659.                MochiServices.disconnect();
  660.                MochiServices.onError("IOError");
  661.             }
  662.             _timer.stop();
  663.          }
  664.       }
  665.    }
  666. }
  667.